package com.guigu.tms.security.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guigu.tms.commons.order.entity.vo.Result;
import com.guigu.tms.commons.security.entity.AuthUser;
import com.guigu.tms.commons.user.entity.Member;
import com.guigu.tms.security.service.IAuthUserService;
import com.guigu.tms.security.util.JwtUtils;
import com.guigu.tms.security.util.ValidateCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

@RestController
@RequestMapping("/courier")
public class CourierAuthController {
    @Autowired
    ValidateCode validateCode;
    @Autowired
    IAuthUserService authUserService;
    @Autowired
    private JwtUtils jwtUtils;

    @PostMapping("checkAuth")
    public Result checkAuth(String token){
        return null;
    }

    //获取验证码
    @GetMapping("getValidateCode")
    public boolean getValidateCode(String phone){
        AuthUser phone1 = authUserService.getOne(new QueryWrapper<AuthUser>().eq("mobile", phone));
        System.out.println(phone1);
        if(phone1==null||phone1.getId().equals("")){
             return false;
        }else {
            validateCode.getValidateCode(phone);
        }
             return true;
    }
    @GetMapping("login")
    public Result courierLogin(String phone,String yanzhen,HttpServletResponse response){
            //查询手机号对应的快递员信息
            AuthUser authUser=authUserService.courierLogin(phone,yanzhen);
            Result result = null;
            if(authUser==null){
                result = Result.error(0,"验证码已过期或者不正确！");
                return result;
            }
            else {
                HashMap<String, Object> map = new HashMap<>();
                map.put("id", authUser.getId());
                map.put("phone", phone);
                String jwt = jwtUtils.generateToken(map);
                response.setHeader("auth", jwt);
                result = Result.ok("登录成功！");
                result.put("authUser", authUser);
                result.put("token", jwt);
                return result;
            }

    }
}
